package com.tensai.teach.beijing.utils.files.model;

import com.tensai.teach.beijing.model.now.Link;
import com.tensai.teach.beijing.model.now.Node;
import com.tensai.teach.beijing.model.now.StreamNode;
import com.tensai.teach.beijing.model.old.base.second.Features;
import com.tensai.teach.beijing.model.old.base.second.features.geometry.JunctionGeo;
import com.tensai.teach.beijing.model.old.base.second.features.properties.JunctionProperties;
import com.tensai.teach.beijing.utils.CommonUtils;
import com.tensai.teach.beijing.utils.data.Relationship;
import com.tensai.teach.beijing.utils.files.LaneService;
import com.tensai.teach.beijing.utils.files.RoadConService;
import com.tensai.teach.beijing.utils.files.RoadService;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Tensai
 */
public class Service {

	private final RoadService roadService = new RoadService();

	private final RoadConService roadConService = new RoadConService();

	private final LaneService laneService = new LaneService();

	public Node makeNode(Features<JunctionProperties, JunctionGeo> junctionFeatures) {
		Long juncId = junctionFeatures.getProperties().getJuncId();
		return Node.builder()
				.id(juncId)
				.name("暂无")
				.inLinks(makeLinkList(juncId))
				.refPos(CommonUtils.getCenter(junctionFeatures.getGeometry()))
				.build();
	}

	public List<Link> makeLinkList(Long juncId) {
		Relationship relationship = Relationship.getRelationshipList().get(juncId);
		Map<String, StreamNode> map = new HashMap<>(8);
		relationship.getRoadFromToList()
				.forEach(it -> map.put(it.getDirection(), StreamNode.builder()
						.id(it.getJunctionId().toString())
						.region("--")
						.phaseId(2L)
						.build()));
		// 左转 右转 直行 掉头 顺序
		String turn = "SWNESWNE";
		return relationship.getRoadFromToList()
				.stream()
				.map(it -> {
					String turn0 = StringUtils.substringAfter(turn, it.getDirection()).substring(0, 4);
					List<StreamNode> streamNodeList = new ArrayList<>();
					for (String s : turn0.split("")) {
						streamNodeList.add(map.get(s));
					}
					List<Long> roadIdList = roadConService.getRoadIdListBetween(it.getFrom(), it.getTo());
					return Link.builder()
							.name(it.getDirection())
							.upstreamNodeId(
									map.get(it.getDirection())
							)
							.speedLimits(roadService.getSpeedLimit(it.getTo()))
							.laneWidth(roadService.getLength(it.getTo()))
							.lanes(laneService.findByRoadId(it.getTo()))
							.roadPoints(roadService.getRoadList(roadIdList))
							.movements(streamNodeList)
							.build();
				})
				.collect(Collectors.toList());

	}
}
